package com.tanhua.manage.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.pojo.User;
import com.tanhua.manage.pojo.UserInfo;
import com.tanhua.manage.vo.Pager;
import com.tanhua.manage.vo.UserInfoVo_six;
import com.tanhua.manage.vo.UserPageVo_six;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UserManageService_six {

    @Autowired
    private UserService_six userService;

    @Autowired
    private UserInfoService_six userInfoService;

    @Autowired
    private LogService_six logService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private UserFreezeService_six userFreezeService;


    /**
     * 用户详细信息
     * @param userId
     * @return
     */
    public UserInfoVo_six queryUserInfoById(Long userId) {
        //验证token
        /*User user = UserThreadLocal.get();
        if (null ==user){
            return null;
        }*/
        try {
            //查出用户表数据
            User nowUser = this.userService.queryUserById(userId);
            if (null == nowUser){
                return null;
            }

            UserInfoVo_six userInfoVo = new UserInfoVo_six();
            //需要user表里的手机,id;
            userInfoVo.setId(Integer.valueOf(nowUser.getId().toString()));
            userInfoVo.setMobile(nowUser.getMobile());
            userInfoVo.setCreated(new DateTime(nowUser.getCreated()).getTime());


            //查询用户信息表
            UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
            if (null != userInfo) {
                //昵称,性别,个性签名,年龄,income,职业occupation,头像
                userInfoVo.setPersonalSignature("皮皮王,我们走");//个性签名,数据库无此字段
                userInfoVo.setNickname(userInfo.getNickName());
                userInfoVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
                userInfoVo.setAge(userInfo.getAge());
                userInfoVo.setIncome(Integer.valueOf(userInfo.getIncome()) * 1000);
                userInfoVo.setOccupation(userInfo.getIndustry());
                userInfoVo.setLogo(userInfo.getLogo());
                userInfoVo.setTags(userInfo.getTags());
            }

            //查询用户操作日志表
            List<Log> userLogs = this.logService.queryLogById(userId);
            if (null != userLogs) {
                //最近活跃时间 最近登录地,注册地区
                userInfoVo.setLastActiveTime(DateUtils.parseDate(userLogs.get(0).getLogTime(), "yyyy-MM-dd").getTime());
                userInfoVo.setLastLoginLocation(userLogs.get(0).getPlace());
                userInfoVo.setCity(userLogs.get(userLogs.size() - 1).getPlace());
            }
            //喜欢数,被喜欢数,互相喜欢数
            userInfoVo.setCountLiked(this.userLikeApi.queryLikeCount(userId).intValue());
            userInfoVo.setCountBeLiked(this.userLikeApi.queryFanCount(userId).intValue());
            userInfoVo.setCountMatching(this.userLikeApi.queryEachLikeCount(userId).intValue());

            //状态
            userInfoVo.setUserStatus(this.userFreezeService.queryUserFreezeById(userId) == null ? "1" : "2");

            return userInfoVo;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 用户数据翻页
     * @param page
     * @param pageSize
     * @param id
     * @param nickname
     * @param city
     * @return
     */
    public Pager<UserPageVo_six> queryPageUser(Integer page, Integer pageSize, Long id, String nickname, String city) {
        //验证token
        /*User user = UserThreadLocal.get();
        if (null ==user){
            return null;
        }*/

        try {
            Pager<UserPageVo_six> pageVo = new Pager<>();

            pageVo.setPage(page);
            pageVo.setPageSize(pageSize);

            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            if (null != id){
                queryWrapper.eq("user_id",id);
            }

            if (null != nickname){
                queryWrapper.like("nick_name",nickname);
            }

            if (null != city){
                queryWrapper.likeRight("city",city);
            }

            IPage<UserInfo> userInfoIPage = this.userInfoService.queryUserInfoList(page, pageSize, queryWrapper);

            //需要返回的用户数据
            List<UserPageVo_six> users = new ArrayList<>();

            pageVo.setCounts(userInfoIPage.getTotal());
            pageVo.setPages(userInfoIPage.getPages());

            //分页之后的所有用户详细信息
            List<UserInfo> userInfos = userInfoIPage.getRecords();

            if (CollectionUtils.isEmpty(userInfos)){
                pageVo.setItems(Collections.emptyList());
                return pageVo;
            }

            //获得需要查询的所有用户的Id集合
            List<Long> ids = new ArrayList<>();

            for (UserInfo userInfo : userInfos) {
                ids.add(userInfo.getUserId());
            }

            //有手机号
            List<User> userList = this.userService.queryUserList(ids);

            //最近活跃时间
            List<Log> userLogList =this.logService.queryLogList(ids);

            for (UserInfo userInfo : userInfos) {
                for (User user : userList) {
                    for (Log log : userLogList) {
                        if (userInfo.getUserId().intValue() == user.getId().intValue()&& userInfo.getUserId().intValue() == log.getUserId().intValue()){
                            UserPageVo_six userPageVo = new UserPageVo_six();
                            userPageVo.setId(user.getId().intValue());
                            userPageVo.setLogo(userInfo.getLogo());
                            userPageVo.setNickname(userInfo.getNickName());
                            userPageVo.setMobile(user.getMobile());
                            userPageVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
                            userPageVo.setAge(userInfo.getAge());
                            userPageVo.setOccupation(userInfo.getIndustry());
                            userPageVo.setUserStatus(this.userFreezeService.queryUserFreezeById(user.getId()) == null ? "1" : "2");
                            userPageVo.setLastActiveTime(DateUtils.parseDate(log.getLogTime(),"yyyy-MM-dd").getTime());
                            userPageVo.setCity(StringUtils.split(userInfo.getCity(), '-')[0]);
                            users.add(userPageVo);
                            break;
                        }
                    }
                }
            }

            pageVo.setItems(users);
            return pageVo;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }
}
